<template>
  <div class="dialog">
    <el-dialog width="55%" :title="title" :visible="true" :close-on-click-modal="false" :before-close="close">
      <el-form ref="form" :model="form" :rules="rules" :disabled="disabled" label-width="120px">
        <el-form-item label="商品图片：" prop="productImages">
          <el-col :span="12">
            <UploadFile :file-list="form.productImages" :disabled="disabled" @change="uploadHandle($event, 'productImages','productImages')">
              <div slot="tip">
                <p>封面690*350px，小于1M的JPG/PNG格式的图片</p>
              </div>
            </UploadFile>
          </el-col>
        </el-form-item>
        <el-form-item label="商品名称：" prop="goodsName">
          <el-col :span="12">
            <el-select v-model="form.goodsName" placeholder="请选择" clearable @change="selectProduct">
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="编号：">
          <el-col :span="12">
            <el-input v-model="form.identifier" placeholder="请输入" clearable disabled />
          </el-col>
        </el-form-item>
        <el-form-item label="购买限制：" prop="count">
          <el-col :span="24">
            每次下单，最少
            <el-input v-model="form.leastCount" v-int class="min-select" placeholder="请输入" clearable />个，最多
            <el-input v-model="form.mostCount" v-int class="min-select" placeholder="请输入" clearable />个
          </el-col>
        </el-form-item>
        <el-form-item label="价格和库存：" prop="price">
          <el-table border :data="[{}]">
            <el-table-column label="零售价（元）">
              <el-input v-model="form.retailPrice" v-money placeholder="请输入" clearable />
            </el-table-column>
            <el-table-column label="门市价（元）">
              <el-input v-model="form.storePrice" v-money placeholder="请输入" clearable />
            </el-table-column>
            <el-table-column label="库存">
              <el-input v-model="form.stock" v-int placeholder="请输入" clearable />
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="运费开关：">
          <el-col :span="12">
            <el-switch v-model="form.freightCode" :active-value="1" :inactive-value="0" />
          </el-col>
        </el-form-item>
        <template v-if="form.freightCode === 1">
          <el-form-item label="距离费用规则：" prop="distance">
            <el-col :span="24">
              <el-input v-model="form.distanceFree" v-money class="min-select" placeholder="请输入" clearable />
              公里免费，以外增加基础配送费
              <el-input v-model="form.distanceDeliveryfee" v-money class="min-select" placeholder="请输入" clearable />
              元/瓶
            </el-col>
          </el-form-item>
          <el-form-item label="上楼费用规则：" prop="floor">
            <el-col :span="24">
              <el-input v-model="form.floorFree" v-int class="min-select" placeholder="请输入" clearable />
              层开始收费，基础配送费
              <el-input v-model="form.floorBasic" v-money class="min-select" placeholder="请输入" clearable />
              元，之后每层增加
              <el-input v-model="form.floorIncrease" v-money class="min-select" placeholder="请输入" clearable />元
            </el-col>
          </el-form-item>
        </template>
      </el-form>
      <div v-if="type !== 'detail'" slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" :loading="loading" @click="confirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDictList } from '@/api/common'
import { creatGasProduct, getGasProductDetail, editGasProduct } from '@/api/product'
import UploadFile from '@/components/UploadFile/index.vue'
import { mapGetters } from 'vuex'
export default {
  name: 'AddProduct',
  components: {
    UploadFile
  },
  props: {
    type: {
      type: String,
      default: 'add' // add:新增  detail:详情  edit:编辑
    },
    id: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    const validateCount = (rule, value, callback) => {
      if (this.form.leastCount && this.form.mostCount) {
        callback()
      } else {
        callback(new Error('请输入购买限制'))
      }
    }
    const validatePrice = (rule, value, callback) => {
      if (this.form.retailPrice && this.form.storePrice && this.form.stock) {
        callback()
      } else {
        callback(new Error('请输入价格和库存'))
      }
    }
    const validateDistance = (rule, value, callback) => {
      if (this.form.distanceFree && this.form.distanceDeliveryfee) {
        callback()
      } else {
        callback(new Error('请输入距离费用规则'))
      }
    }
    const validateFloor = (rule, value, callback) => {
      if (this.form.floorFree && this.form.floorBasic && this.form.floorIncrease) {
        callback()
      } else {
        callback(new Error('请输入上楼费用规则'))
      }
    }
    return {
      productList: [],
      loading: false,
      form: {
        productImages: '',
        goodsName: '',
        identifier: '',
        leastCount: '',
        mostCount: '',
        retailPrice: '',
        storePrice: '',
        stock: '',
        freightCode: 0,
        distanceFree: '',
        distanceDeliveryfee: '',
        floorFree: '',
        floorBasic: '',
        floorIncrease: ''
      },
      rules: {
        productImages: [{ required: true, message: '请上传商品图片', trigger: ['change'] }],
        goodsName: [{ required: true, message: '请选择商品名称', trigger: ['change'] }],
        count: [{ required: true, validator: validateCount, trigger: ['blur'] }],
        price: [{ required: true, validator: validatePrice, trigger: ['blur'] }],
        distance: [{ required: true, validator: validateDistance, trigger: ['blur'] }],
        floor: [{ required: true, validator: validateFloor, message: '', trigger: ['blur'] }]
      }
    }
  },

  computed: {
    ...mapGetters([
      'currentEnterprise',
      'currentSite'
    ]),
    title() {
      if (this.type === 'detail') {
        return '商品详情'
      } else if (this.type === 'edit') {
        return '编辑商品'
      } else {
        return '发布商品'
      }
    },
    disabled() {
      return this.type === 'detail'
    }
  },

  created() {
    this.getDictList()
    if (this.id) {
      this.getDetail()
    }
  },

  methods: {

    // 获取商品列表
    getDictList() {
      const data = {
        dictClass: 'gas_qp_product_type'
      }
      getDictList(data).then(res => {
        this.productList = res || []
      }).catch(() => {})
    },

    // 选择商品
    selectProduct(name) {
      const result = this.productList.find(item => item.name === name)
      this.form.identifier = result?.value || ''
    },

    // 获取详情
    getDetail() {
      const data = {
        id: this.id
      }
      getGasProductDetail(data).then(res => {
        const {
          productImages,
          goodsName,
          identifier,
          leastCount,
          mostCount,
          retailPrice,
          storePrice,
          stock,
          freightCode = 0,
          distanceFree,
          distanceDeliveryfee,
          floorFree,
          floorBasic,
          floorIncrease
        } = res
        this.form = {
          productImages,
          goodsName,
          identifier,
          leastCount,
          mostCount,
          retailPrice,
          storePrice,
          stock,
          freightCode,
          distanceFree,
          distanceDeliveryfee,
          floorFree,
          floorBasic,
          floorIncrease
        }
      }).catch(() => {})
    },

    // 取消
    close() {
      this.$emit('close')
    },

    // 确认
    confirm() {
      if (this.type === 'add') {
        this.addHandle()
      } else {
        this.editHandle()
      }
    },

    // 新增
    addHandle() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          const data = {
            siteId: this.currentSite.id,
            ...this.form
          }
          creatGasProduct(data).then(() => {
            this.$message.success('新增成功')
            this.loading = false
            this.$emit('confirm')
            this.close()
          }).catch(() => {
            this.loading = false
          })
        } else {
          return false
        }
      })
    },

    // 编辑
    editHandle() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          const data = {
            ...this.form,
            id: this.id,
            siteId: this.currentSite.id
          }
          editGasProduct(data).then(() => {
            this.$message.success('编辑成功')
            this.loading = false
            this.$emit('confirm')
            this.close()
          }).catch(() => {
            this.loading = false
          })
        } else {
          return false
        }
      })
    },

    // 上传图片处理
    uploadHandle(payload, name, prop) {
      const fileList = payload.fileList
      const result = []
      fileList.map(item => {
        result.push(item.url)
      })
      this.form[name] = result.join(',')
      this.$refs.form.validateField(prop)
    }
  }

}
</script>

<style lang="scss" scoped>
.el-select{
  width: 100%;
}
.min-select{
  width: 110px;
  padding: 0 10px;
}

</style>
